<template>
  <ArtTableFullScreen>
    <div id="table-full-screen">
      <el-card shadow="never" class="art-table-card">
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <template #left>
            <el-button @click="showDialog('add')" :icon="Plus">新增</el-button>
          </template>
        </ArtTableHeader>
        <art-table
          :data="tableData"
          :loading="loading"
          :currentPage="queryParams.page"
          :pageSize="queryParams.size"
          :total="total"
          @size-change="getTableData"
          @current-change="getTableData"
        >
          <template #default>
            <el-table-column v-for="col in columns" :key="col.prop" v-bind="col" />
          </template>
        </art-table>

        <el-dialog
          v-model="dialogVisible"
          :title="dialogType === 'add' ? '新增活动' : '修改活动'"
          width="40%"
        >
          <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="80px"
            :disabled="disabled"
          >
            <el-form-item label="日期" prop="date">
              <el-date-picker
                v-model="formData.date"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                range-separator="至"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="链接" prop="url">
              <el-input
                v-model="formData.url"
                placeholder="请输入链接地址"
                class="input-with-select"
              >
                <template #prepend>
                  <el-select v-model="routes" style="width: 115px">
                    <el-option
                      v-for="(item, index) in restaurants"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-input>
            </el-form-item>

            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="封面" prop="cover">
                  <ArtImageUpload v-model:files="formData.cover"></ArtImageUpload>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="人数" prop="views">
                  <el-input-number
                    v-model="formData.views"
                    style="width: 100%"
                    :min="1"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入活动标题" />
            </el-form-item>
            <el-form-item label="副标题" prop="subtitle">
              <el-input v-model="formData.subtitle" placeholder="请输入活动副标题" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="formData.sort" :min="1" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSubmit" :disabled="disabled">提交</el-button>
            </div>
          </template>
        </el-dialog>
      </el-card>
      <Annex ref="annexRef" :type="1"></Annex>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { FormInstance } from 'element-plus'
  import { ElMessageBox, ElMessage, ElTag, ElButton } from 'element-plus'
  import type { FormRules } from 'element-plus'
  import { ContentService } from '@/api/common'
  import { Plus, Delete, Edit, View, Document } from '@element-plus/icons-vue'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import ArtImagePreview from '@/components/image/ArtImagePreview.vue'

  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const loading = ref(false)
  const total = ref(0)
  const tableData = ref<any>([])
  const annexRef = ref(null)
  const disabled = ref(false)

  const formData = reactive({
    date: [],
    url: '',
    cover: '',
    views: 1000,
    title: '',
    subtitle: '',
    sort: 10,
    cate_id: 8
  })

  const routes = 'https://'

  const restaurants = reactive([
    { label: '本地', value: 'com.hn.qingnai.ui.activity.' },
    { label: '自定义', value: '自定义' }
  ])

  const queryParams = reactive({
    page: 1,
    size: 10,
    cate_id: 8
  })
  // 列配置
  const columnOptions = [
    { label: '勾选', type: 'selection' },
    { label: 'ID', prop: 'id' },
    { label: '封面', prop: 'cover' },
    { label: '标题', prop: 'title' },
    { label: '副标题', prop: 'subtitle' },
    { label: '状态', prop: 'status' },
    { label: '参与人数', prop: 'views' },
    { label: '创建日期', prop: 'create_time' },
    { label: '操作', prop: 'operation' }
  ]

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    { type: 'selection' }, // 勾选列
    // { type: 'expand', label: '展开', width: 80 }, // 展开列
    // { type: 'index', label: '序号', width: 80 }, // 序号列
    { prop: 'id', label: 'ID' },
    {
      prop: 'cover',
      label: '封面',
      formatter: (row: any) => {
        return h(ArtImagePreview, { src: row.cover })
      }
    },
    { prop: 'title', label: '标题' },
    { prop: 'subtitle', label: '副标题' },

    {
      prop: 'status',
      label: '状态',
      formatter: (row: any) => {
        return h(ElTag, { type: getTagType(row) }, () => buildTagText(row))
      }
    },
    { prop: 'views', label: '参与人数' },
    {
      prop: 'create_time',
      label: '创建日期',
      sortable: true
    },
    {
      prop: 'operation',
      label: '操作',
      width: 200,
      align: 'center',
      fixed: 'right', // 固定在右侧
      // disabled: true,
      formatter: (row: any) => {
        return h('div', { class: 'option' }, [
          h(
            ElButton,
            {
              size: 'small',
              icon: Edit,
              text: true,
              onClick: () => showDialog('edit', row)
            },
            () => '编辑'
          ),
          h(
            ElButton,
            {
              size: 'small',
              type: 'danger',
              icon: Delete,
              text: true,
              onClick: () => deleteTableRow(row)
            },
            () => '删除'
          ),
          h(
            ElButton,
            {
              size: 'small',
              icon: View,
              text: true,
              onClick: () => showDialog('detail', row)
            },
            () => '详情'
          ),
          h(
            ElButton,
            {
              size: 'small',
              icon: Document,
              text: true,
              onClick: () => showAnnex(row)
            },
            () => '附件'
          )
        ])
      }
    }
  ])

  onMounted(() => {
    getTableData()
  })

  const handleRefresh = () => {
    getTableData()
  }
  // 获取商品列表
  const getTableData = async () => {
    loading.value = true
    const { data } = await ContentService.getListContent(queryParams)
    const res = data.data.filter((item: any) => item.state !== -2)
    total.value = data.total
    tableData.value = res
    loading.value = false
  }

  // 显示附件弹窗
  const showAnnex = (row: any) => {
    annexRef.value.openList(row.id, row.cover)
  }
  const setFormData = (row: any) => {
    formData.date = row.start_time && row.end_time ? [row.start_time, row.end_time] : []
    formData.url = row.url !== null ? row.url.replace(routes, '') : ''
    formData.cover = row.cover
    formData.title = row.title
    formData.subtitle = row.subtitle
    formData.views = row.views
    formData.sort = row.sort
    formData.id = row.id
  }
  const showDialog = (type: string, row?: any) => {
    dialogVisible.value = true
    dialogType.value = type
    if (type === 'edit' && row) {
      setFormData(row)
      disabled.value = false
    } else if (type === 'detail') {
      setFormData(row)
      disabled.value = true
    } else {
      formData.date = []
      formData.url = ''
      formData.title = ''
      formData.cover = ''
      formData.subtitle = ''
      formData.views = 1000
      formData.sort = 10
      formData.id = ''
      disabled.value = false
    }
  }

  const deleteTableRow = (row: any) => {
    ElMessageBox.confirm('确定要删除该活动吗？', '删除活动', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })
      .then(() => {
        return ContentService.deleteContent(row.id)
      })
      .then(() => {
        getTableData()
        ElMessage.success('删除成功')
      })
  }

  const getTagType = (row: any) => {
    const curTime = Date.now() //当前时间戳
    const startTime = new Date(row.start_time).getTime()
    const endTime = new Date(row.end_time).getTime()
    if (curTime <= endTime && curTime >= startTime) {
      return 'success'
    } else if (curTime > endTime) {
      return 'danger'
    } else if (curTime < startTime) {
      return 'info'
    } else {
      return 'warning'
    }
  }

  const buildTagText = (row: any) => {
    const curTime = Date.now() //当前时间戳
    const startTime = new Date(row.start_time).getTime()
    const endTime = new Date(row.end_time).getTime()
    let status = ''
    if (curTime <= endTime && curTime >= startTime) {
      status = '进行中'
    } else if (curTime > endTime) {
      status = '已结束'
    } else if (curTime < startTime) {
      status = '未开始'
    } else {
      status = '已结束'
    }
    return status
  }

  const rules = reactive<FormRules>({
    date: [{ required: true, message: '请选择时间', trigger: 'blur' }],
    url: [{ required: true, message: '请输入链接', trigger: 'blur' }],
    cover: [{ required: true, message: '请选择封面', trigger: 'blur' }],
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    subtitle: [{ required: true, message: '请输入副标题', trigger: 'blur' }]
  })

  const formRef = ref<FormInstance>()

  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (valid) {
        if (dialogType.value === 'add') {
          await ContentService.addContent(formData)
        } else {
          await ContentService.updateContent(formData)
        }
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        await getTableData()
        dialogVisible.value = false
      }
    })
  }
</script>

<style lang="scss" scoped>
  :deep(.option .el-button + .el-button) {
    margin-left: 0;
  }
</style>
